import json
import socket

from aiohttp_cors import web

from utils.get_threshold_image import get_threshold_image
from utils.handle_binary_image_entry import handle_binary_image_entry
from utils.image2numpy import image2numpy
from utils.plots.stream_plot import stream_plot_3d
from utils.plots.stream_plot_2d import stream_plot_2d
from utils.read_tar_files import read_tar_files
from utils.recognize_texts_with_picture_2 import recognize_texts_with_picture_2

image_info = {}
hostname0 = socket.gethostname()
local_ip = socket.gethostbyname(hostname0)
print(local_ip)

# read_tar_files()
handle_binary_image_entry()
# stream_plot_3d()
# stream_plot_2d()
async def websocket_handler(request):
    print('Websocket server has heard.')
    ws = web.WebSocketResponse()
    await ws.prepare(request)
    text_info = ''
    async for msg in ws:
        print(f'msg.type: {msg.type}')
        if msg.type == web.WSMsgType.TEXT:
            json_content = json.loads(msg.data)
            json_id = json_content['id']
            if json_id == 'imageToText': #图像识别文本
                image_data = json_content['src']
                npimage = image2numpy(image_data)
                image_info['image'] = npimage
                text_info = recognize_texts_with_picture_2(npimage)
            elif json_id == 'handleImage':
                text_info = get_threshold_image(image_info['image'], json_content)
            await ws.send_str(text_info)



app = web.Application()
app.add_routes([
    web.get('/font/{uploadType}/{suffix}', websocket_handler)
])

web.run_app(app, port=8000)